#include <iostream>
#include <memory>
#include <cassert>
#include <malloc.h>
#include "account.h"
#include <unistd.h>

Account *create_account(int code, double balance)
{

    Account *a = (Account *)malloc(sizeof(Account));
    assert(a != NULL);
    a->code = code;
    a->balance = balance;
    pthread_mutex_init(&a->mutex, NULL);
}

//销毁账户
void destroy_account(Account *a)
{

    assert(a != NULL);
    pthread_mutex_destroy(&a->mutex);
    free(a);
}

//取款
double withdraw(Account *a, double amt)
{
    pthread_mutex_lock(&a->mutex); //对共享资源进行枷锁
    if (amt < 0 || amt > a->balance)
    {
        pthread_mutex_unlock(&a->mutex);
        return 0.0;
    }
    //取款
    double balance = a->balance; // balance是账户余额 amt是要取多少钱
    sleep(1);
    balance -= amt;
    a->balance = balance;
    pthread_mutex_unlock(&a->mutex);
    return amt;
}

//存款
double deposit(Account *a, double amt)
{
    // a不能为空
    assert(a != NULL);
    //代码临界区
    pthread_mutex_lock(&a->mutex);

    if (amt < 0)
    {

        pthread_mutex_unlock(&a->mutex);
        return 0.0;
    }

    double balance = a->balance;

    balance += amt;
    pthread_mutex_unlock(&a->mutex);
    return amt;
}

//查看账户余额
double get_balance(Account *a)
{
    pthread_mutex_lock(&a->mutex);
    double balance = a->balance;
    std::cout << "账户余额是：" << a->balance << std::endl;
    pthread_mutex_unlock(&a->mutex);
    return balance;
}
